const express = require('express');
const { createServer } = require('http');
const path = require('path');
const { WebSocketServer } = require('ws');
const machineRoute = require('./routes/machine');
const machineService = require('./service/machine');
const utils = require('./utils');

// 设备数据初始化
machineService.init();

const app = express();
// 配置静态文件目录
app.use(express.static(path.join(__dirname, '/static')));

// 加载路由器
machineRoute(app, 'machine');

// 利用现成的server创建 ws 服务
const server = createServer(app);
const wss = new WebSocketServer({ server, path: '/api/machine/status' });

// ws 链接监听
wss.on('connection', (ws) => {
  console.log('wss-connection');
  const aListener = (status) => {
    // 设备启动/停止成功后的监听器-给client发送状态
    ws.send(status);
  }
  // 添加监听器
  utils.addListen(aListener);
  ws.on('message', function message(data) {
    console.log('message', data);
  });
  ws.on('close', () => {
    console.log('wss-closed');
    // 移除监听器
    utils.removeListen(aListener);
  })
});

// 服务启动监听
server.listen(8080, () => {
  console.log('server is running on 8080');
})